package try01;

import java.util.*;

/*
The idea of the solution is to set four boundaries, r1 r2 c1 c2
after program check for a row, r1 or r2 will move to prevent checking that row again
the same thing for the column
*/

public class SpiralMatrix {
	public void tester() {
		int [][] a = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}};
		List<Integer> b = spiralOrder(a);
		System.out.println(b);
		System.out.println("size: "+b.size());
	}
	
    public List<Integer> spiralOrder(int[][] matrix) {
    	List <Integer> result = new LinkedList<Integer> ();
    	
    	if(matrix.length == 0) return result;
    	
        int r1 = 0, r2 = matrix.length - 1;
        int c1 = 0, c2 = matrix[0].length - 1;
        
        int r = 0, c = 0;
        
        while(r1 <= r2 && c1 <= c2) {
        	while(r1<=r2 && c <= c2) {
            	result.add(matrix[r][c]);
            	c++;
            }
            r1++;
            c--;
            r++;
            
            while(c1<=c2 && r <= r2) {
            	result.add(matrix[r][c]);
            	r++;
            }
            r--;
            c2--;
            c--;
            
            while(r1<=r2 && c >= c1) {
            	result.add(matrix[r][c]);
            	c--;
        	}
        	c++;
        	r2--;
        	r--;
            
        	while(c1<=c2 && r >= r1) {
            	result.add(matrix[r][c]);
            	r--;
            }
            r++;
            c1++;
            c++;
            
//            System.out.println(r1+" "+r2+" "+c1+" "+c2);
        }
        
        return result;
    }
}